<?php
/**
 * （logic）转款报告（amazon）
 * sr:settlement-deposit-last
 */
namespace App\Logic\SalesReport;

use App\Models\SalesReport\FBADeposit;
use Illuminate\Support\Facades\DB;
class SrFBASettlementDepositLast
{
    public static function exe(){
        try{
            $start = date('Y-m-01 00:00:00',strtotime('midnight first day of -1 month'));
            FBADeposit::query()->where('deposit_date','>=',$start)->update(['status' => 0]);
            sleep(10);
            $res = FBADeposit::query()->where('status',0)->get();
            $data = [];
            foreach ($res as $re){
                $date = date('Y-m',strtotime($re->deposit_date));
                $data[$date.'_'.$re->account_id.'_'.$re->country_id][] = $re->settlement_id;
            }
            $temps = [];
            foreach ($data as $settlementIds){
                $max = max($settlementIds);
                $temp = [];
                foreach ($settlementIds as $settlementId){
                    $temp['settlement_id'] = $settlementId;
                    if($settlementId == $max){
                        $temp['status'] = 1;
                    }else{
                        $temp['status'] = 2;
                    }
                    $temps[] = $temp;
                }
            }
            DB::beginTransaction();
            $i = 0;
            $num = 50;
            while (true){
                if(empty($temps))break;
                $_temps = array_splice($temps,$i,$num);
                $sql = "UPDATE fba_settlement_deposit SET status = CASE settlement_id ";
                $_settlementIds = [];
                foreach ($_temps as $_temp){
                    $_settlementIds[] = $_temp['settlement_id'];
                    $sql .= sprintf("WHEN %s THEN %d ", $_temp['settlement_id'], $_temp['status']);
                }
                $sql .= "END WHERE settlement_id IN (".implode(',',$_settlementIds).")";
                DB::connection('mysql_amazon')->update(DB::raw($sql));
                DB::commit();
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
